package com.laker.autotest.desktop.core;

import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Mat;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import javax.imageio.ImageIO;

/**
 * OpenCV 图像识别工具类
 */
public class DesktopImageUtil {
    static {
        // 加载 OpenCV 库
        nu.pattern.OpenCV.loadLocally();
    }

    /**
     * 屏幕截图并保存到文件
     */
    public static String captureScreen(String filePath) {
        try {
            Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
            BufferedImage bufferedImage = new Robot().createScreenCapture(screenRect);
            ImageIO.write(bufferedImage, "png", new File(filePath));
            return filePath;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 在屏幕截图中查找模板图片，返回左上角坐标
     * @param templatePath 模板图片路径
     * @return 匹配到的左上角坐标，未找到返回 null
     */
    public static Point findImageOnScreen(String templatePath) {
        String screenPath = "_opencv_screen.png";
        captureScreen(screenPath);
        Mat screen = Imgcodecs.imread(screenPath);
        Mat template = Imgcodecs.imread(templatePath);
        if (screen.empty() || template.empty()) {
            return null;
        }
        int resultCols = screen.cols() - template.cols() + 1;
        int resultRows = screen.rows() - template.rows() + 1;
        Mat result = new Mat(resultRows, resultCols, CvType.CV_32FC1);
        Imgproc.matchTemplate(screen, template, result, Imgproc.TM_CCOEFF_NORMED);
        Core.MinMaxLocResult mmr = Core.minMaxLoc(result);
        if (mmr.maxVal >= 0.95) { // 匹配阈值可调整
            return mmr.maxLoc;
        }
        return null;
    }
}

